var oriData = null; 
var _grid = null;
var $queryWindow;  //查询窗口对象
function initGridData(id,type){
	if(_grid){
		$("#grid-table").jqGrid('setGridParam', 
				{
		postData:{areaId : id,atype :type,queryJsonString:"" },
				}
		).trigger("reloadGrid");
		return;
	}
	_grid = jQuery("#grid-table").jqGrid({
		/*url : "http://"+ip+":"+port+"/"+name+"/bindings/list.do?interfaceAuthority="+interfaceAuthority,*/
		url: context_path + '/wmsshevle/shevleList',
        datatype: "json",
        postData:{areaId : id,atype :type },
	    colNames : [ '主键','货架编号','货架名称','行','列','位','所属库区','混放策略','出入库锁','ABC分类','承载量','备注','操作'],
	       colModel : [ 
	                    {name : 'id',index : 'id',sortable: false,width : 60,hidden:true},
	                    {name : 'shevelNo',index : 'shevelNo',sortable: false,width : 40},
	                    {name : 'shevelName',index : 'shevelName',sortable: false,width : 40},
	                    {name : 'row_number',index : 'row_number',sortable: false,width : 40},
	                    {name : 'line_number',index : 'line_number',width : 40,sortable: false,hidden:true},
	                    {name : 'place_number',index : 'place_number',sortable: false,width : 80},
	                    {name : 'areaName',index : 'areaName',sortable: false,width : 80},
	                    {name : 'confusionMethod',index : 'confusionMethod',sortable: false,width : 80},
	                    {name : 'locked',index : 'locked',sortable: false,width : 80},
	                    {name : 'classify',index : 'classify',sortable: false,width : 80},
	                    {name : 'carryingCapacity',index : 'carryingCapacity',sortable: false,width : 80},
	                    {name : 'remark',index : 'remark',sortable: false,width : 80},
//	                	{ name: 'Edit', index: 'Edit', sortable: false,  width: 120,
//	                    	formatter:function(cv,options,row){
//	                    		var editBtn = "";
//	                    		if(row.device_addr && row.device_addr.length==4){//主控制器
//	                    			editBtn = "<div id='dopt_btn_"+row.id+"' class='btn btn-xs btn-danger opt_btn_"+row.id+"' onclick='operatAll(this.id,"+row.id+",2)' >全部下架</div>&nbsp;"+
//		                    		"<div id='uopt_btn_"+row.id+"' class='btn btn-xs btn-success opt_btn_"+row.id+"' onclick='operatAll(this.id,"+row.id+",1)' >全部上架</div>";
//		                    	}else if(row.device_addr && row.device_addr.length==8){//层控制器
//		                    		editBtn = "<div id='dopt_btn_"+row.id+"' class='btn btn-xs btn-danger opt_btn_"+row.id+"' onclick='operatAll(this.id,"+row.id+",2)' >全部下架</div>&nbsp;"+
//		                    		"<div id='uopt_btn_"+row.id+"' class='btn btn-xs btn-success opt_btn_"+row.id+"' onclick='operatAll(this.id,"+row.id+",1)' >全部上架</div>";
//		                    		
//		                    	}else if(row.device_addr && row.device_addr.length==12){//未控制器
//		                    		if(row.epc || row.epc.length>0){
//		                    			editBtn = "<div id='opt_btn_"+row.id+"' class='btn btn-xs btn-danger' onclick='operatshelve(this.id,"+row.id+",2)' >下架</div>";
//		                    		}
//		                    		if(!row.epc || row.epc.length==0){
//		                    			editBtn = "<div id='opt_btn_"+row.id+"' class='btn btn-xs btn-success' onclick='operatshelve(this.id,"+row.id+",1)' >上架</div>";
//		                    		}
//		                    	}
//	                    		
//	                    		return editBtn;
//	                    	}	
//	                    },
	                    { name: 'Edit', index: 'Edit', sortable: false,  width: 120,
	                    	formatter:function(cv,options,row){
	                    		editBtn = "<div id='"+row.id+"' class='btn btn-xs btn-success' onclick='openVisual(this.id)' >可视化</div>";
	                    		return editBtn
	                    	}
	                    }
	                  ],
	    rowNum : 20,
	    rowList : [ 10, 20, 30 ],
	    pager : '#grid-pager',
	    sortname : 'id',
	    sortorder : "desc",
        altRows: true,
        viewrecords : true,
        caption : "货架列表",
        hidegrid:false,
        /* 	       autowidth:true, */
        multiselect:true,
        loadComplete : function(data) 
        {
        	var table = this;
        	setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
        	oriData = data;
        },
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext : "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据"
	});
	
	jQuery("#grid-table").navGrid('#grid-pager',{edit:false,add:false,del:false,search:false,refresh:false})
	.navButtonAdd('#grid-pager',{  
		caption:"",   
		buttonicon:"fa fa-refresh green",   
		onClickButton: function(){   
			$("#grid-table").jqGrid('setGridParam', 
					{
			postData:{areaId : getSelectNodeId().id,atype :getSelectNodeId().atype,queryJsonString:"" },
					}
			).trigger("reloadGrid");
		}
	});

	$(window).on('resize.jqGrid', function () {
		$("#grid-table").jqGrid( 'setGridWidth', $(window).width()-$("#sidebar").width() -200);
		$("#grid-table").jqGrid( 'setGridHeight', ($(window).height()-$("#table_toolbar").outerHeight(true)- $("#grid-pager").outerHeight(true)-$("#user-nav").height()-$("#breadcrumb").height()-$(".ui-jqgrid-labels").height()-35 ) );
	});

	$(window).triggerHandler('resize.jqGrid');
}




//重新加载表格
function gridReload()
{
	_grid.trigger("reloadGrid");  //重新加载表格  
}


/**
 * 查询功能:获取查询页面中的值，并将值放入列表页面中隐藏的form
 * @param jsonParam     查询页面传递过来的json对象
 */
function queryLogListByParam(jsonParam){
	var queryJsonString = JSON.stringify(jsonParam);         //将json对象转换成json字符串
	//执行查询操作
	$("#grid-table").jqGrid('setGridParam', 
			{
		postData: {queryJsonString:queryJsonString} //发送数据 
			}
	).trigger("reloadGrid");
}

/**
 * 查询按钮点击事件
 */
function openQueryPage(){
	var queryParam = iTsai.form.serialize($('#query_form'));
	queryLogListByParam(queryParam);
}

//全部上架
function operatAll(elementid,bid,operation){
	var btnclass = elementid.substring(1);
	$("."+btnclass).attr("disabled","disabled");
	$("#"+elementid).html("进行中");
	$.ajax({
		url:"http://"+ip+":"+port+"/"+name+"/light/batchShelveByaddr?interfaceAuthority="+interfaceAuthority,
		type:"POST",
		data:{bid : bid, operationType: operation},
		datatype:"JSON",
		success:function(data){
			$("."+btnclass).removeAttr("disabled");
			if(elementid.startWith("u")){
				$("#"+elementid).html("全部上架");
			}else{
				$("#"+elementid).html("全部下架");
			}
			if (data.result){
				layer.msg(data.msg,{icon:1});
			}
		}
	});
}


//打开可视化页面
function openVisualPage(){
	//清空浏览器缓存
	/*localStorage.removeItem("selectTreeId");
	localStorage.removeItem("selectTreeType");
	for ( let int = 0,$catchCount = localStorage.length; int < $catchCount; int++) {
	localStorage.removeItem(localStorage.key(int));
	}
*/	
	localStorage.clear();//清除浏览器缓存
	var windowH = $(window).height();
	var windowW = $(window).width();
	layer.open({
		  type: 2,
		  title: '仓库可视化',
		  shadeClose: true,
		  shade: false,
		  maxmin: false, //开启最大化最小化按钮
		  area: [windowW+'px', windowH+'px'],
		  //content: context_path+"/warehouse/displayindex"
		  content: context_path+"/wmsbind/toVisualPage"
		  /*content: context_path+"/baseinfo/shevelGoods/display-index.jsp"*/
		});
}

function openVisual(id){
	localStorage.clear();//清除浏览器缓存
	var windowH = $(window).height();
	var windowW = $(window).width();
	layer.open({
		  type: 2,
		  title: '货架可视化',
		  shadeClose: true,
		  shade: false,
		  maxmin: false, //开启最大化最小化按钮
		  area: [windowW+'px', windowH+'px'],
		  //content: context_path+"/warehouse/displayindex"
		  content: context_path+"/wmsbind/toVisual?id="+id
		  /*content: context_path+"/baseinfo/shevelGoods/display-index.jsp"*/
		});
}

//位控制器上下架
function operatshelve(elementid,id,operation){
	$("#"+elementid).attr("disabled","disabled");
		$.ajax({
			url:"http://"+ip+":"+port+"/"+name+"/light/getBindDeviceById?interfaceAuthority="+interfaceAuthority,
			type:"POST",
			data:{id : id},
			datatype:"JSON",
			success:function(data){
				console.dir(data);
				$("#"+elementid).removeAttr("disabled");
				if(data){
					if(data.status!=1 && data.status!=2 && data.status!=5){
						if(operation==1){
							//上架：不能有物料
						if(!data.epc || data.epc.length==0){
							f_doshelve(data.device_addr,operation,data.wirless_addr,1);
	 						}else{
	 							//有物料，不能上架
	 							layer.msg("该库位上有物料，不能进行上架操作！",{icon:2});
	 						}
						}else if(operation==2){
							//下架：有物料
						if(data.epc && data.epc.length>0){
							f_doshelve(data.device_addr,operation,data.wirless_addr,1);
	 						}else{
	 							//没物料，不能下架
	 							layer.msg("该库位上没有物料，不能进行下架操作！",{icon:2});
	 						}
						}
					}else{
						var msg = data.status==1?"正在上架":(data.status==2?"正在下架":(data.status==5?"设备故障":""));
						layer.msg(msg+"，请稍后重试！",{icon:2});
					}
				}
			}
			
		});
	}
	
	//上下架操作
	//operationType:1上架，2下架，operation：1开，2关
	function f_doshelve(addr,operationType,ant,operation) {
	     $.ajax({
	         type: "POST",
	         url: "http://"+ip+":"+port+"/"+name+"/light/shelve?interfaceAuthority="+interfaceAuthority,
	         datatype: 'json',
	         cache: false,
	         data:{addr:addr,deviceType:operationType,ant:ant,operation:operation},
	         success: function (data) {
	             if (data == "0") {
	            	 layer.msg("命令发送成功！",{icon:1,time: 1000});
	             } else if (data == "1") {
	            	 layer.msg("命令发送失败！",{icon:2,time: 1000});
	             }
	         }
	     });
	   }
    
var zTree;   //树形对象
var selectTreeId = 0;   //存放选中的树节点id
var selectTreeType = 1; //存放的节点类型
var selectTreeNode = null; //存放点击的树节点
//树的相关设置
var setting = {
    check: {
        enable: true	
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    edit: {
        enable: false,
        drag:{
        	isCopy:false,
        	isMove:false
        }
    },
    callback: {
		onClick: zTreeOnClick,
		onAsyncSuccess: zTreeOnAsyncSuccess
    },
	async: {
		enable: true,
		url:context_path+"/wmsshevle/treeData",
		autoParam:["id"],
		type: "POST"
	},//异步加载数据
};

/**
 * 获取树中选中节点的id
 * @returns {Number}
 */
function getSelectNodeId(){
	var selectNode = {id:null,atype:0};
	if(zTree){
		var nodes = zTree.getSelectedNodes();
		if(nodes.length>0){
			selectNode.id =  nodes.id;
			console.log(selectNode.id);
			selectNode.atype = nodes.atype;
		}
	}
	
	return selectNode;
}

//ztree加载成功之后的回调函数
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	zTree.expandAll(true);
	var datalist = JSON.parse(msg);
	//默认点击第一个
    if(datalist.length>0){
    	console.dir(datalist);
    	var clickNode = zTree.getNodeByParam("id", datalist[0].id, null);
    	clickNode.click = zTreeOnClick(null,null,clickNode);
    	zTree.selectNode(clickNode);
    }
};

//树节点click事件
function zTreeOnClick(event, treeId, treeNode) {
	//节点点击事件 alert(treeNode.tId + ", " + treeNode.name);
	//后台获取相应工程的地图数据
	var selectnodes = zTree.getSelectedNodes();  //选中的节点
	selectTreeId = treeNode.id;   //记录每次点击的树节点
	selectTreeType = treeNode.atype;
	selectTreeNode = treeNode;    //记录每次点击的树节点所有数据
	//根据点击的货架，获取货架列表
	/*$("#grid-table").jqGrid('setGridParam',
            {
                postData: {areaId: treeNode.id,atype:treeNode.atype, queryJsonString: ""} //发送数据
            }
    ).trigger("reloadGrid");*/
	if(selectTreeType == 0){
		$("#visualOpration").attr("style","display:none");
	}else{
		$("#visualOpration").removeAttr("style","display:none");
	}
	initGridData(selectTreeId,selectTreeType);
};


//初始化树
$.fn.zTree.init($("#areaTreeDiv"), setting);
zTree = $.fn.zTree.getZTreeObj("areaTreeDiv");
	